<template>
  <div class="avatar-upload">
    <!-- 头像和添加头像在同一行 -->
    <div class="avatar-row">
      <!-- 显示当前头像，点击打开预览弹窗 -->
      <img
        :src="props.avatarUrl"
        alt="用户头像"
        class="avatar-img"
        @click="showPreview = true"
      />

      <!-- 上传组件：点击触发文件选择 -->

      <!-- 支持任意的图片格式 -->
      <a-upload
      name="avatar"
      :show-upload-list="false"
      :action="uploadUrl"
      :before-upload="beforeUpload"
      @change="handleChange"
      :headers="uploadHeaders"
        :capture="null"
      >
        <div class="upload-trigger">设置头像</div>
      </a-upload>
    </div>

    <!-- 预览弹窗 -->
    <a-modal v-model:visible="showPreview" title="头像预览" footer="null">
      <img :src="props.avatarUrl" alt="头像预览" class="preview-img" />
    </a-modal>
  </div>
</template>

<script setup>
import { message } from "ant-design-vue";
  import { ref } from 'vue';
import { saveAvatarUrl } from '../../api/modules/api_user_avatar';
import { GetToken } from '../../utils/storage';
  // 定义组件属性
  const props = defineProps({
    avatarUrl: {
      type: String,
      default: ''
    }
  })
  const uploadUrl=import.meta.env.VITE_BACKEND_URL+"my/uploadAvatar"
  // 上传头像时的请求头
  const uploadHeaders = {
    Authorization: GetToken()
  }
  // 预览弹窗状态
const showPreview = ref(false);
const emit = defineEmits(['update:avatarUrl']); // 定义事件发射器
// 四、上传前验证
// =====================
const beforeUpload = (file) => {
  const isImage =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/jpg";
  if (!isImage) {
    message.error("只能上传 JPG/PNG 图片！");
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片大小不能超过 2MB！");
    return false;
  }

  return true;
};
const handleChange = (info) => {
  if (info.file.status === 'done') {
    // 上传成功
    const response = info.file.response;
    if (response.status === 200) {
      // 后端返回的URL是相对路径，需要加上基础URL才能正确访问
      const newAvatarUrl = import.meta.env.VITE_BACKEND_URL + response.data.url;
      // console.log('上传成功，新头像URL:', newAvatarUrl);
      // 1. 通知父组件更新头像 URL (用于页面预览)
      emit('update:avatarUrl', newAvatarUrl);

      // 2. (可选但推荐) 调用后端接口保存 URL 到数据库
      // 注意：保存到数据库时仍然使用相对路径
      saveAvatarToDB(response.data.url);

    } else {
      // 后端返回了错误
      message.error(response.data?.message || '上传失败');
    }
  } else if (info.file.status === 'error') {
    // 上传失败
    message.error(`${info.file.name} 上传失败.`);
  }
};

// 调用后端保存头像 URL 的函数
const saveAvatarToDB = async (avatarUrl) => {
  try {
    const res = await saveAvatarUrl({ avatarUrl });
    if (res.status === 200) {
      message.success('头像已保存到数据库');
    } else {
      message.error(res.data?.message || '保存头像到数据库失败');
    }
  } catch (error) {
    console.error('保存头像到数据库时出错:', error);
    message.error('保存头像到数据库时发生错误');
  }
};



</script>

<style scoped>
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

/* 头像和添加头像在同一行 */
.avatar-row {
  display: flex;
  align-items: center;
  gap: 15px;
  justify-content: center;
}

.avatar-img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  cursor: pointer;
  object-fit: cover;
}

/* 上传组件样式 */
.upload-trigger {
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
  font-size: 14px;
  color: #666;
}

.upload-trigger:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.preview-img {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  display: block;
}
</style>
